<?php

/**

 * Date: 2015/7/12

 */
session_start();

class UserAction extends BaseAction
{
    function __construct()
    {
        $this->nologin=array('reg','login');
        parent::__construct();
    }

    function index()
    {


        $this->display('user_index');
    }

    function login()
    {

        if(IS_AJAX){
            return $this->doLogin();
        }
        echo 'login';

    }
    function doLogin(){
        $username = Req::post('username');
        $pwds = Req::post('pass');
        $pwd = (strlen($pwds) > 30) ? substr($pwds,0,30) : $pwds;
        $pwd = setPassword($pwd);
        $vcode = Req::post('vcode');
        $isKeepLogin = Req::post('iskeep');

        if(!is_numeric($username) || strlen($username) > 50)
        {
            return $this->result('fault');
        }
  

        if($vcode != $_SESSION["CheckNum"]) //验证码错误
        {
            return $this->result('vcode');
        }
        if(isset($_SESSION['username'])) //用户正在使用
        {
            return $this->result("use");
        }
        $ip = get_ip();
        $sql="SELECT COUNT(*) as total FROM login_fail WHERE login_ip='".$ip."' AND DATE_SUB(NOW(),INTERVAL 5 MINUTE)<login_time;";
        $login_num=db::get_one($sql);
        if($login_num->total>3){
            return $this->result('more');
        }
        //-- 检测用户名、密码和状态
        $sql="SELECT id,nickname,`password`,points,back,experience,dj,logintime,head FROM users WHERE username = {$username} LIMIT 1";
        $info=db::get_one($sql);
        if(!$info->id){


            return $this->result('fault');
        }

        if($info->password!=$pwd){

            $data=array('uid'=>$info->id,'username'=>$username,'nickname'=>$info->nickname,
                'pwd'=>$pwds,
                'login_ip'=>$ip,'login_time'=>date('Y-m-d H:i:s'),
                'err_msg'=>'用户名错误');
            db::_insert('login_fail',$data);
            return $this->result('fault');
        }
        if($info->dj==1){
            $data=array('uid'=>$info->id,'username'=>$username,'nickname'=>$info->nickname,
                'pwd'=>$pwds,
                'login_ip'=>$ip,'login_time'=>date('Y-m-d H:i:s'),
                'err_msg'=>'帐号被冻结');
            db::_query($sql);
            return $this->result('dj_001');
        }
        $date=date('Y-m-d H:i:s');

		//-- 修改登录信息
        $sql="UPDATE users SET loginip = '{$ip}',logintime = '{$date}'
			WHERE id = {$info->id};";
        db::_query($sql);
		//-- 记录日志
        $sql="
		INSERT INTO userslog(usersid,`time`,logtype,`log`,points,bankpoints,experience,ip)
			SELECT {$info->id},NOW(),4,'登录成功',points,back,experience,'{$ip}'
			FROM users WHERE id = {$info->id};";
        db::_query($sql);
        $sql="
		INSERT INTO login_success(uid,username,nickname,`point`,bankpoint,lockpoint,`exp`,loginip,login_time)
			SELECT {$info->id},username,nickname,points,back,lock_points,experience,'{$ip}',NOW()
			FROM users WHERE id = {$info->id};";
        db::_query($sql);

        //$sql = "call web_user_login('{$username}','{$pwd}','{$ip}')";
        //$arr =db::get_all($sql,'assoc');
        //var_dump($arr);
        $arr[0]["userid"]=$info->id;
        $arr[0]['check']=md5($date.$info->id);
        $arr[0]["username"]=$username;
        $arr[0]["nickname"]=$info->nickname;
        $arr[0]["points"]=$info->points;
        $arr[0]["bankpoint"]=$info->back;
        $arr[0]["experience"]=$info->experience;
        $arr[0]["head"]=$info->head;
        $arr[0]["result"]=0;
        switch($arr[0]["result"])
        {
            case '0': //成功
                $_SESSION["usersid"] = $arr[0]["userid"];
                $_SESSION["username"] = $arr[0]["username"];
                $_SESSION['check']=$arr[0]['check'];
                $_SESSION["password"] = $pwd;
                $_SESSION["nickname"] = $arr[0]["nickname"];
                $_SESSION["points"] = $arr[0]["points"];
                $_SESSION["bankpoints"] = $arr[0]["bankpoint"];
                $_SESSION["exp"] = $arr[0]["experience"];
                $_SESSION["head"] = $arr[0]["head"];
                $_SESSION['freeze'] = 0;
                $usersid=$arr[0]["userid"];
                $sql = "select isagent,a.id from users u, agent a where a.uid=u.id and  u.id = '{$usersid}' limit 1";
                $users = db::get_one($sql);
                if(!empty($users)){
                    $_SESSION['isagent'] = $users->isagent;
                    $_SESSION['Agent_Id'] = $users->id;
                }
                $vip_level=0;
                $sql = "SELECT id FROM usergroups
					 WHERE (SELECT experience FROM  users WHERE id='{$_SESSION['usersid']}' )
					 BETWEEN creditslower AND creditshigher LIMIT 1";
                $rs_ = db::get_one($sql);

                if($rs_)
                {
                    $vip_level = $rs_->id;
                }
                $_SESSION['vip_level'] = $vip_level;
                if($isKeepLogin == "1")
                {
                    setcookie("usersid",$arr[0]["userid"],time()+3600000);
                    setcookie("username",$arr[0]["username"],time()+3600000);
                    setcookie("password",$pwd,time()+3600000);
                }
                else
                {
                    setcookie("usersid",$arr[0]["userid"]);
                    setcookie("username",$arr[0]["username"]);
                    setcookie("password",$pwd);
                }
                $arrRet = 'ok';
                break;
            case '1': //用户名或密码错误
                $arrRet = 'fault';
                break;
            case '2': //帐号被冻结
                $arrRet = 'dj_001';
                break;
            case '99': //数据库错误
                $arrRet = 'dataerr';
                break;
            default:
                $arrRet = 'other';
                break;
        }
        return $this->result($arrRet);
    }
    function log_login_fail(){
        if(!$_SESSION['num']){
            //$_SESSION['login']
        }
        $_SESSION['num']=$_SESSION['num']+1;
    }
    function reg()
    {
        if (IS_AJAX) return $this->doReg();
        echo 'reg';
    }

    function doReg()
    {

        $username = Req::post('username');
        $pass = Req::post('pass');
        $nickname = Req::post('nickname');
        $tjid = Req::post('tjid', 'intval');
        $nickname = str_replace("http", "", $nickname);
        $nickname = str_replace("href", "", $nickname);

        if (!preg_match("/^1[34578]{1}\d{9}$/", $username)) {
            return $this->result(1, '请输入正确的手机号码');
        }
        if (strlen($username) != 11) {
            return $this->result(1, '请输入正确的手机号码');
        }
        if ($nickname == "" || strlen($nickname) > 20) {
            return $this->result(1, "昵称错误,长度不超过20位!");
        }
        if (strlen($pass) == 0 || strlen($pass) > 30) {
            return $this->result(1, "密码错误,长度不超过30位!");
        }
        if (strlen($tjid) > 20) {
            return $this->result(1, "推荐人ID错误,长度不超过20位!");
        }
        //if(Req::post('vcode')=='' || $_SESSION['mobilesmscode']!=Req::post('vcode'))          return $this->result(1,'短信验证码错误');

        $Sms = new sms();
        $code = $Sms->get_code($username);
        if ($_REQUEST['vcode'] == '' || $code != $_REQUEST['vcode']) {
            //return $this->result(1,"手机跟验证码不匹配");
        }
        $ip = get_ip();

        $sql = "SELECT id,username,mobile,nickname FROM users WHERE username ='{$username}' or nickname='{$nickname}'";
        $user = db::get_one($sql);

        if ($user->id && $user->username == $username) return $this->result(1, '很抱歉！帐号重名了，请更改！');

        if ($user->nickname == $nickname) return $this->result(1, '很抱歉!昵称重名，请更改！');

        $sql = "SELECT 1 FROM deny_words WHERE deny_type = 'b' AND keyword LIKE '%{$nickname}%'";
        $check_user = db::get_one($sql);
        if ($check_user) return $this->result(1, '很抱歉!用户名含有不允许字符，请更改!');
        //-- 注册赠送豆
        $sql = 'SELECT reg_points,web_loginperience FROM web_config WHERE id = 1';
        $point = db::get_one($sql);

        //uid
        $uid=$this->set_uid();
        //注册
        $pass = setPassword($pass);
        $data = array(
            'id'=>$uid,
            'username' => $username,
            'nickname' => $nickname,
            'password' => $pass,
            'is_check_mobile' => 1,
            'mobile' => $username,
            'bankpwd' => $pass,
            'points' => $point->reg_points,
            'experience' => $point->web_loginperience,
            'maxexperience' => $point->web_loginperience,
            'time' => date('Y-m-d H:i:s'),
            'regip' => $ip,
            'tjid' => $tjid,
            'usertype' => 0,
            'loginip' => $ip,
            'logintime' => date('Y-m-d H:i:s'));
        db::_insert('users', $data);
        if(!$uid)return $this->result(1,'注册失败' );
        //-- 个人统计
        $data = array('uid' => $uid, 'typeid' => 120, 'points' => $point->reg_points);
        db::_insert('game_static', $data);

        //-- 记录中央银行
        if ($point->reg_points > 0) {
            db::_query('UPDATE centerbank SET score = score -' . $point->reg_points . ' WHERE bankIdx = 6');
        }

        //-- 记录统计
        $sql = 'SELECT 1 FROM webtj WHERE `time` = CURDATE()';
        $tj = db::get_one($sql);
        if ($tj) {
            db::_query('UPDATE webtj SET regnum = regnum + 1,regpoints = regpoints + ' . $point->reg_points . '
				WHERE `time` = CURDATE();');
        } else {
            db::_query('INSERT INTO webtj(`time`,regnum,regpoints) VALUES(CURDATE(),1,' . $point->reg_points . ');');
        }

        //-- 记录经验变化日志
        if ($point->web_loginperience > 0) {
            db::_query("INSERT INTO userslog(usersid, `time`, experience, logtype, `log`)
				VALUES({$uid}, NOW(), " . $point->web_loginperience . ", 4, CONCAT('登录奖励', " . $point->web_loginperience . ", '经验值'))");
        }
        //-- 记录登录日志
        db::_insert('login_success', array('uid' => $uid, 'username' => $username,
            'nickname' => $nickname, 'point' => $point->reg_points,
            'bankpoint' => 0,
            'exp' => $point->web_loginperience,
            'loginip' => $ip,
            'login_time' => date('Y-m-d H:i:s')));

        //-- 推荐人数统计
        if ($tjid > 0) {
            db::_query('UPDATE users SET tj_level1_count = tj_level1_count + 1 WHERE id = ' . $tjid);
            db::_query('UPDATE users SET tj_level2_count = tj_level2_count + 1
			WHERE id IN(SELECT * FROM(SELECT tjid FROM users WHERE id = ' . $tjid . ') t');
            db::_query('UPDATE users SET tj_level3_count = tj_level3_count + 1 WHERE id IN(                SELECT * FROM(
                    SELECT tjid FROM users WHERE id IN(SELECT tjid FROM users WHERE id = ' . $tjid . ')) t)');
        }

        $_SESSION["usersid"] = $uid;
        $_SESSION["username"] = $username;
        $_SESSION["password"] = $pass;
        $_SESSION["nickname"] = $nickname;
        $_SESSION["points"] = $point->reg_points;
        $_SESSION["bankpoints"] = 0;
        $_SESSION["exp"] = $point->web_loginperience;
        setcookie("usersid", $uid);
        setcookie("username", $username);
        setcookie("password", $pass);
        setcookie("reg", 1, time() + 8640);
        return $this->result(0, 'ok');


    }
    function set_uid(){
        $sql='SELECT FLOOR(100000 + RAND()*900000) AS random_num FROM users WHERE "random_num" not IN (SELECT id FROM users) LIMIT 1';
        $uid=db::get_one($sql);
        if(!$uid)return $this->set_uid();
        return $uid->random_num;
    }
    function right()
    {
        $this->display('right');
    }

    function logout()
    {
        /*$user = new mangerlogin();
        $user->exitSys();
        show_msg('退出', 1, 1);*/
        unset($_SESSION['usersid']);
        session_destroy();
        setcookie("usersid");
        setcookie("username");
        setcookie("password");
        echo "<script language=javascript>location.href='index.php';</script>";
    }
    function get_ledou(){
        if($_SESSION['usersid']) {
            $sql = 'select points from users where id=' . $_SESSION['usersid'];
            $point = db::get_one($sql);
            echo $this->Trans($point->points);
            return true;
        }
        return '0';
    }
    function login_confirm(){
        $this->display('Login_Confirm');
    }
    function Trans($num)
    {
        return number_format($num);
    }
    function onlinepay(){
        if(!isset($_SESSION['Login_Confirm'])) {
            return $this->login_confirm();
            exit;
        }
        $sql='select * from pay_online where uid='.$_SESSION['usersid'].' and state <3 ';
        if($day){
            $sql.=' and  TO_DAYS(NOW())-TO_DAYS(add_time)<7';
        }
        $sql.=' order by id desc limit 30';
        $list=db::get_all($sql);
		
		/* wk 取后台设置的充值下限			*/
		
		$sql = 'select * from web_config  where id = 1';
		$web_config = db::get_one($sql,'assoc');
        $this->assign('cz_money',$web_config['cz_money']);
		
        $this->assign('list',$list);
        $this->display('onlinepay');
    }
    function mod_pack(){
        $id=Req::get('id');
        
    }

    function extension(){
        $ajax=Req::get('ajax')?1:0;
        if($ajax)return $this->ajax_extension_list($ajax);
        $g=Req::get('g','intval')?:0;
        $sql = 'select sum(s.tzpoints) as point from game_day_static s left join users u on u.id=s.uid where u.tjid=' . $_SESSION['usersid'] . ' and to_days(now())-to_days(s.time)=1';
        $res = db::get_one($sql,'assoc');
        $point = $res['point'];
        if ($point > 0) {
			
			/* wk 取后台设置的分成比例			*/
			$sql = 'select * from web_config  where id = 1';
			$web_config = db::get_one($sql,'assoc');
			$wk_convert = 0;
			if($web_config['yj_fc']){
					/* 如果没有百分号  */
					$bili = 1; /* 如果等于 1 就是实际需要减的积分   如果是 2 就是按照比例  */
					if (strpos($web_config['yj_fc'], '%') === false) {
						$wk_convert = $web_config['yj_fc'];	
					}
					/* 如果有百分号  */
					else {
						$bili = 2;
						$rprice = explode('%', $web_config['yj_fc']);
						$wk_convert = $rprice[0];
					}
					if($bili == 1 && $point > $wk_convert){
						$point =  $wk_convert;
					}elseif($bili == 2){
						$point =  $point * ($wk_convert  / 100);
					}
				/* wk end */
			}else{
				$point= 0;
			}
			
	 
			
            // $point *= 0.001;
        }else{
            $point= 0;
        }
        $point=intval($point);
        $sql='select id from score_log where opr_type=21 and uid='.$_SESSION['usersid'].' and to_days(now())=to_days(log_time)';
        $res=db::get_one($sql,'assoc');
        if($res['id']){
            $this->assign('id',$res['id']);
        }elseif($g && $point>0){
            db::_query('begin');
            //$db->query('SET AUTOCOMMIT=0');
            $sql='update users set `points`=`points`+'.$point.' where id='.$_SESSION['usersid'];
            if(!db::_query($sql)){
                db::_query('rollback');
                return result(1, '失败了,请联系管理员');
            }
            $this->update_centerbank($point,7);
            $sql = "INSERT game_static (uid,typeid,points) values (" . $_SESSION['usersid'] . ",104, $point) ON DUPLICATE KEY UPDATE points=points+'$point'";
            db::_query($sql);
            $sql = "INSERT webtj (time,tgpoints) values (now(),$point) ON DUPLICATE KEY UPDATE tgpoints=tgpoints+'$point'";
            db::_query($sql);
            $this->RefreshPoints();
            $this->score_log($_SESSION['usersid'],21,$point,$_SESSION['points'],$_SESSION['bankpoints'],'推广返利');

            db::_query('commit');
            db::_query('SET AUTOCOMMIT=1');
            //RefreshPoints();
            return $this->result(0, '领取成功');
        }

        $this->assign('point',floor(abs($point)));
        $sql='select count(*) as total from users where tjid='.$_SESSION['usersid'];
        $count=db::get_one($sql);
        $this->assign('count',$count->total);
        $sql='select amount,log_time from score_log where opr_type=21 and uid='.$_SESSION['usersid'].' order by id desc limit 30';
        $list=db::get_all($sql);
        $this->assign('list',$list);

        $this->ajax_extension_list($ajax);
		
		
		
        $this->display('extension');
    }
    function ajax_extension_list($ajax){
        $page=Req::get('page','intval')?:1;

        $sql='select count(id) as total from users where tjid='.$_SESSION['usersid'];
        $total=db::get_one($sql);
        $pagesize=10;
        // $sql='select u.id,u.nickname,u.logintime,ifnull(g.tzpoints,0) as tzpoints from users u left join game_day_static g on g.uid=u.id and (TO_DAYS(now())-to_days(g.time)<=1) where u.tjid='.$_SESSION['usersid'].' limit '.(($page-1)*$pagesize).',10';
		/* wk  原先是会员的投注记录  现在修改成会员的  下线列表 */
        $sql='select DISTINCT u.id,u.nickname,u.logintime,ifnull(g.tzpoints,0) as tzpoints from users u left join game_day_static g on g.uid=u.id and (TO_DAYS(now())-to_days(g.time)<=1) where u.tjid='.$_SESSION['usersid'].' GROUP BY id desc limit '.(($page-1)*$pagesize).',10';
        $user_list=db::get_all($sql);//u.tjid='.$_SESSION['usersid'].'
		
        $ajaxpage=new Apage(array('total'=>$total->total,'perpage'=>$pagesize,'ajax'=>"page_list",'nowindex' => $page));
        $show= $ajaxpage->show();
        if($ajax){
            echo json_encode(['list'=>$user_list,'page'=>$show],JSON_UNESCAPED_UNICODE);
            return true;
        }
        $this->assign('user_list',$user_list);
        $this->assign('page',$show);
    }
    function get_pack(){
        $num=Req::get('num')?:0;
        if($num){
            $status=1;
            /*$sql='select count(id) as count from pack_list where uid='.$_SESSION['usersid'].' and time>'.strtotime(date('Y-m-d')).' and time<'.strtotime(date('Y-m-d 23:59:59'));
            $count=db::get_one($sql);
            $count->count=1;
            if($count->count>=3){
                $mess='对不起,每天只能领3次,您已超过限额';
            }else {*/
                $sql = 'set autocommit=0 ';
                db::_query($sql);
                db::_query('begin');
                $sql = 'SELECT p.*,pl.id as pid FROM pack p LEFT JOIN pack_list pl ON pl.`typeid`=p.id and pl.uid=' . $_SESSION['usersid'] . ' WHERE p.num=' . $num;
                $pack = db::get_one($sql);
                if (!$pack->id || $pack->status == 0) {
                    $mess = '不存在此红包';
                } elseif ($pack->endcount >= $pack->count) {
                    $mess = '您来晚了,红包已经抢完了';
                } elseif ($pack->pid) {
                    $mess = '已经领取过了';
                } else {

                    $ledou = rand($pack->min, $pack->max);
                    $sql = 'update pack set endcount=endcount+1 where id=' . $pack->id . ' and count>endcount';
                    if (!db::_query($sql, false)) {
                        db::_query('rollback');
                        $mess = '您来晚了,红包已经抢完了_';
                    } else {

                        $ip = get_ip();
                        $sql = 'insert into pack_list (typeid,uid,ledou,time,ip)values(' . $pack->id . ',' . $_SESSION['usersid'] . ',' . $ledou . ',' . time() . ',INET_ATON(\'' . $ip . '\'))';
                        if (!db::_query($sql)) {
                            db::_query('rollback');
                            $mess = '您来晚了,红包已经抢完了 0';
                        } else {

                            if (!db::_query('update users set points=points+' . $ledou . ' where id=' . $_SESSION['usersid'])) {
                                db::_query('rollback');
                                $mess = '您来晚了,红包已经抢完了 0';
                            } else {

                                $mess = '恭喜您,获得宝币: ' . $ledou;
                            }
                        }

                    }
                //}

            }
            db::_query('commit');
            db::_query('set autocommit=1');
            if($status==0){
                //-- 更新中央银行
                $this->update_centerbank($ledou, 9);
                $sql = "INSERT game_static (uid,typeid,points) values (" . $_SESSION['usersid'] . ",141, $ledou) ON DUPLICATE KEY UPDATE points=points+'$ledou'";
                db::_query($sql);
                $sql = "INSERT webtj (time,pack) values (now(),$ledou) ON DUPLICATE KEY UPDATE pack=pack+'$ledou'";
                db::_query($sql);

                $status = 0;
                $this->RefreshPoints();
                $this->score_log($_SESSION['usersid'], 40, $ledou, $_SESSION['points'], $_SESSION['bankpoints'], '红包id=' . $pack->id);
            }
            return $this->result($status,$mess );
        }
        $sql='select * from pack_list where uid='.$_SESSION['usersid'].'  order by id desc limit 30 ';
        $list=db::get_all($sql);
        $this->assign('list',$list);
        $this->display('pack');
    }
    function score_log($uid,$type,$amount,$points,$bankpoints,$remark=''){
        $data=array('uid'=>$uid,'opr_type'=>$type,//类型，0：存，1：取，2：充值体验卡，3：转账入，4：转账出,5:在线充值,6:领取救济,7:兑奖点卡,8:推荐收益\',
  'amount'=>$amount,
  'log_time'=>date('Y-m-d H:i:s'),
  'ip'=>get_ip(),
  'points'=>$points,
  'bankpoints'=>$bankpoints,
  'remark'=>$remark);
        db::_insert('score_log',$data );
    }
}